﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace FBA.Client.Utils
{
    /// <summary>
    /// vm控制view控件获取焦点
    /// </summary>
  public static class FocusBehavior
    {
        private static Dictionary<UIElement, RoutedEventHandler> handlers =
            new Dictionary<UIElement, RoutedEventHandler>();
        public static bool? GetIsFocused(DependencyObject obj)
        {
            return (bool?)obj.GetValue(IsFocusedProperty);
        }
        public static void SetIsFocused(DependencyObject obj, bool? value)
        {
            obj.SetValue(IsFocusedProperty, value);
        }
        public static readonly DependencyProperty IsFocusedProperty =
                DependencyProperty.RegisterAttached(
                "IsFocused",
                typeof(bool?),
                typeof(FocusBehavior),
                new UIPropertyMetadata()
                {
                    DefaultValue = null,
                    PropertyChangedCallback =
                        (s, e) => {
                            UIElement sender = (UIElement)s;
                            RoutedEventHandler x;
                            if (!handlers.TryGetValue(sender, out x))
                            {
                                Attach(sender);
                            }
                            if ((bool)e.NewValue)
                            {
                                sender.Focus();
                                Keyboard.Focus(sender);
                            }
                        }
                });
        private static void Attach(UIElement sender)
        {
            RoutedEventHandler handler = (s, e) => {
                UIElement ui = (UIElement)s;
                if (e.RoutedEvent == UIElement.GotFocusEvent)
                {
                    ui.SetValue(IsFocusedProperty, true);
                }
                if (e.RoutedEvent == UIElement.LostFocusEvent)
                {
                    ui.SetValue(IsFocusedProperty, false);
                }
            };
            sender.GotFocus += handler;
            sender.LostFocus += handler;
            handlers.Add(sender, handler);
        }
    }
}
